<?php
/**
 * Created by PhpStorm.
 * User: Neho
 * Date: 2018/2/28
 * Time: 16:54
 */

namespace app\api\logic;

use think\Model;
use \think\Loader;
use app\common\model\User as UserModel;

class WechatEntry extends Model
{
    protected $userModel;
    protected $wechatOauthService;

    protected function initialize()
    {
        parent::initialize();
        $this->userModel = Loader::model('User', 'model');
        $this->wechatOauthService = Loader::model('WechatOauth', 'service');
    }

    /**
     *  微信登录
     * @param $code ,前端返回的code
     * @return array
     */
    public function login($code)
    {
        $userInfo = $this->wechatOauthService->userInfo($code);
        if (!empty($userInfo)) {
            $isRegist = $this->userModel->isRegist($userInfo['openid']);
            if (!$isRegist) {
                $this->startTrans();
                try {
                    $this->userModel->user_nick_name = $userInfo['nickname'];
                    $this->userModel->user_avatar = $userInfo['headimgurl'];
                    if ($this->userModel->save()) {
                        $auth = [
                            'identity_type' => 3,
                            'identifier' => $userInfo['openid']
                        ];
                        if ($this->userModel->userAuth()->save($auth)) {
                            $this->commit();
                            $data = array(
                                'userId' => $this->userModel->id,
                            );
                            return $data;
                        }
                    }
                } catch (\Exception $e) {
                    $this->rollback();
                }
            } else {
                $user = UserModel::hasWhere('userAuth', ['identifier' => $userInfo['openid']])->find();
                $data = array(
                    'userId' => $user['id'],
                );
                return $data;
            }
        }
    }
}
